﻿$.MGJ.AuthList_V = [];
var uploadList = [];
(function () {
    var _this = $.MGJ.AuthList_V;
    $.extend($.MGJ.AuthList_V, {
        conditionModel: {
            page: 1,
            pageSize: 10,
            searchKey: null,//查询条件
        },
        AuthModel:{
            Id: 0,
            AuthName:"",
            Category:0
        },
        Dialog_AuthAdd_VObj: null,
        Dialog_AuthAdd_V: function (obj) {
            this.Dialog_AuthAdd_VObj = $.L.dialog({
                url: ACTION_URL("AuthAdd_V", "Auth"),
                title: "添加认证",
                width: 700,
                height: 500,
                buttons: {
                    //"button_save": {
                    //    type: 'primary',
                    //    text: '保存',
                    //    click: function () {
                    //        $.L.msgError(1)
                    //    }
                    //},
                    "button_cancel": {
                        type: 'default',
                        text: '关闭',
                        click: function () {
                            _this.Dialog_AuthAdd_VObj.close();
                            $.MGJ.AuthList_V.Ajax_GetAuthPageList(1);
                        }
                    }
                }
            });
        },
        Dialog_AuthEdit_VObj: null,
        Dialog_AuthEdit_V: function (obj) {
            var authId = $(obj).attr("Id");
            this.Dialog_AuthEdit_VObj = $.L.dialog({
                url: ACTION_URL("AuthAdd_V", "Auth") + "?Id=" + authId,
                title: "编辑认证",
                width: 700,
                height: 500,
                buttons: {
                    //"button_save": {
                    //    type: 'primary',
                    //    text: '保存',
                    //    click: function () {
                    //        $.L.msgError(1)
                    //    }
                    //},
                    "button_cancel": {
                        type: 'default',
                        text: '关闭',
                        click: function () {
                            _this.Dialog_AuthEdit_VObj.close();
                            $.MGJ.AuthList_V.Ajax_GetAuthPageList(1);
                        }
                    }
                }
            });
        },

        Ajax_GetAuthModelByAuthId:function(authId){
            $.L.ajaxHandle({
                url: ACTION_URL("GetAuthModelByAuthId", "Auth")+"?authId="+authId,
                success: function (response) {
                    var authModel = response;
                    $("#AuthId").val(authModel.Id);
                    $("#AuthName").val(authModel.AuthName);
                    $("#Category").val(authModel.Category);
                }
            });
        
        },

        Ajax_GetAuthModuleListByAuthId: function (authId) {
            $.L.ajaxHandle({
                url: ACTION_URL("GetAuthModuleListByAuthId", "AuthModule") + "?Id=" + authId,
                success: function (response) {
                    var pickerNub;

                    //if (response.length == 0) {
                    //    return;
                    //}
                    $("#ListWrap").empty();
                    var list = response;
                    var html = "";
                    var innerHtml = "";

                    for (var i = 0; i < list.length; i++) {
                        pickerNub = 100 + i;
                        innerHtml += [
                 '<form role="form">',
                 '<input type="hidden" name="id" value="' + list[i].Id + '">',
                 '<div class="row" style="margin-top:15px;">',
             '<div class="col-xs-12 col-md-12" style="position:relative">',
                 '<div class="col-xs-5 col-md-5">',
                     '<div id="thelist' + pickerNub + '" class="uploader-list" style="display:flex;align-items:center">',

                         '<input type="hidden"  name="Picture" value="'+list[i].Picture+'"  />' ].join("");

                        if (list[i].Picture!=null) {
                            innerHtml += ['<div id="picker' + pickerNub + '"class="picker"  style="background: url(' + list[i].Picture + ');background-size:100% 100%;width:200px;height:200px;border-radius:5px;background-repeat:no-repeat"></div>'].join("");
                        } else {
                            innerHtml += ['<div id="picker' + pickerNub + '"class="picker"  style="background: url(/Content/webImgs/upLogo/cp_img_tj.png);background-size:100% 100%;width:200px;height:200px;border-radius:5px;background-repeat:no-repeat"></div>'].join("");
                        }

                        innerHtml += ['  </div>',
                 '</div>',
                 '<div class="col-xs-7 col-md-7" style="position:relative;">',
                     '<input type="text"  name="ModuleName" class="form-control" placeholder="输入名称(如企业荣誉)" style="margin-bottom:10px;"  value=' + list[i].ModuleName + '>',
                     '<textarea class="form-control" name="Content" placeholder="输入描述" value=' + list[i].Content + '>' + list[i].Content + '</textarea>',
                     '<div class="row">'].join("");

                        if (list[i].IsH5 == 0) {
                            innerHtml += [
                         '<span class="col-xs-4 col-md-4">是否显示：</span>',
                        '<div class="col-xs-4 col-md-4"><input type="radio" checked  value="0"  name="IsH5" /> 是</div>',
                        '<div class="col-xs-4 col-md-4"><input type="radio"  value="1" name="IsH5" /> 否</div>'
                            ].join("");
                        } if (list[i].IsH5 == 1) {
                            innerHtml += [
                           '<span class="col-xs-4 col-md-4">是否显示：</span>',
                          '<div class="col-xs-4 col-md-4"><input type="radio"  value="0" checked name="IsH5" /> 是</div>',
                          '<div class="col-xs-4 col-md-4"><input type="radio" checked  value="1" name="IsH5" /> 否</div>'
                            ].join("");
                        }

                        innerHtml += [
                       '</div>',
                        ' <div class="row">',

                        '<button class="btn btn-primary" type="button" data-id="' + list[i].Id + '" onclick="$.MGJ.AuthList_V.ValidatorModuleSave(this)" style="float:right;margin-right:80px;">保存</button>',
                        //'<button class="btn btn-primary" type="button" onclick="$.MGJ.AuthList_V.AddRow()" style="float:right;margin-right:80px;">添加</button>',
                         '<button class="btn btn-primary" type="button" data-id="' + list[i].Id + '" onclick="$.MGJ.AuthList_V.Ajax_AuthModuleDelete(this)" style="float:right;margin-right:80px;">删除</button>',
                    '</div>',


                    '</div>',
                '</div>',
            '</div>',

            '</form>'

                        ].join("");

                        $("#ListWrap").append(innerHtml);
                        html += innerHtml;
                        innerHtml = "";

                        uploadList[pickerNub] = WebUploader.create({
                            // swf文件路径
                            //swf: BASE_URL + '/js/Uploader.swf',
                            // 文件接收服务端。
                            //server: 'DBH/UploadImgPath' + "?path=" + path + "&fname=ImageUrl1",

                            server: '/Upload/Upload/',
                            // 选择文件的按钮。可选。 内部根据当前运行是创建，可能是input元素，也可能是flash.
                            pick: {
                                id: '#picker' + pickerNub,
                                multiple: false
                            },
                            accept: {
                                title: 'Images',
                                extensions: 'gif,jpg,jpeg,bmp,png',
                                mimeTypes: 'image/jpg,image/jpeg,image/png'
                            },
                            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                            resize: false
                        });
                        LoadItem(uploadList[pickerNub], '#thelist' + pickerNub, '#picker' + pickerNub);

                    }
                }
            });


        },

        //Ajax_AuthDelete: function (obj) {
        //    var authId = $(obj).attr("Id");
        //},

        Ajax_GetAuthPageList: function (pageindex) {

            _this.conditionModel.page = pageindex || 1;
            _this.conditionModel.searchKey = $("#SearchKey").val();
            $.L.ajaxHandle({
                url: ACTION_URL("GetAuthPageList", "Auth"),
                data: _this.conditionModel,
                success: function (response) {
                    $("#PageList").L_bindingDataList(response);
                }
            });

        },


        Ajax_AuthModuleDelete: function (obj) {
         
            var authId = $("#AuthId").val();
            var moduleId = $(obj).parents("form").children("input[name='id']").val();
            if (moduleId == 0) {
                _this.Ajax_GetAuthModuleListByAuthId(authId);
                return;
            }


            $.L.ajaxHandle({
                url: ACTION_URL("AuthModuleDelete", "AuthModule"),
                data: {moduleId:moduleId},
                success: function (response) {
                    if (response > 0) {
                        _this.Ajax_GetAuthModuleListByAuthId(authId);
                    }
                }
            });
        },

        ValidatorModuleSave: function (obj) {
            var bootstrapValidator = $("#firstForm").data('bootstrapValidator').validate();
            if (bootstrapValidator.isValid()) {
                _this.Ajax_AuthSave(obj)
            }
            else {
                $.L.msgError("请检查数据格式！");
            };
        },

        Ajax_AuthSave:function(obj){
            var authId = $("#AuthId").val();
            var AuthName = $("#AuthName").val();
            var Category = $("#Category").val();

            if (AuthName == "") {
                alert("请填写认证名称");
                return;
            }

            _this.AuthModel.Id = authId;
            _this.AuthModel.AuthName = AuthName
            _this.AuthModel.Category = parseInt(Category);
            
            //if (authId == 0) {
         
                $.ajax({
                    url: ACTION_URL("AuthSave", "Auth"),
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: "{\"model\":" + JSON.stringify(_this.AuthModel) + "}",
                    success: function (response) {
                        $.MGJ.AuthList_V.Ajax_GetAuthPageList(1);
                        if (response > 0) {
                            $("#AuthId").val(response);
                            _this.Ajax_AuthModuleSave(obj);
                        } else {
                            $.L.msgError("认证记录创建失败，请检查网络稍后再试！")
                            return;
                        }
                    }
                });

            //} else {
            //    _this.Ajax_AuthModuleSave(obj);
            //}
        
        },

        Ajax_AuthModuleSave: function (obj) {
            var authModule = $(obj).parents("form").serializeObject();
            if (authModule.ModuleName == "") {
                authModule.ModuleName = " ";
            }
            if (authModule.Content == "") {
                authModule.Content = " ";
            }
            var authId = $("#AuthId").val();
            authModule.AuthId = authId;

            $.L.ajaxHandle({
                url: ACTION_URL("AuthModuleSave", "AuthModule"),
                data: authModule,
                success: function (response) {
                    if (response > 0) {
                        if (authModule.id == 0 && response > 1) {
                          
                            $(obj).parents("form").children("input[name='id']").val(response);
                        }
                        $.L.msgSuccess("保存成功");
                    } else {
                        $.L.msgError("认证模块保存失败，请检查网络刷新页面后重试！")
                        return;
                    }
                }
            });

        },

        CategoryName: function (val) {

            if (val == 0) {
                return "企业证照"
            } else if (val == 1) {
                return "质检报告"
            }
            else if (val == 2) {
                return "荣誉证书"
            }else {
                return "其他"
            }

        },



        AddRow: function () {

        pickerNub++
        var html = [
            '<form role="form">',

            '<input type="hidden" name="id" value="0">',

            '<div class="row" style="margin-top:15px;">',
        '<div class="col-xs-12 col-md-12" style="position:relative">',
            '<div class="col-xs-5 col-md-5">',
                '<div id="thelist' + pickerNub + '" class="uploader-list" style="display:flex;align-items:center">',

                '<input type="hidden"  name="Picture" value=""  />',

                    '<div id="picker' + pickerNub + '"class="picker"  style="background: url(\'/Content/webImgs/upLogo/cp_img_tj.png\' );background-size:100% 100%;width:200px;height:200px;border-radius:5px;background-repeat:no-repeat"></div>',
              '  </div>',
            '</div>',
            '<div class="col-xs-7 col-md-7" style="position:relative;">',
                '<input type="text" name="ModuleName" class="form-control" placeholder="输入名称(如企业荣誉)" style="margin-bottom:10px;">',
                '<textarea class="form-control" name="Content" placeholder="输入描述" ></textarea>',
                '<div class="row">',
                   '<span class="col-xs-4 col-md-4">是否显示：</span>',
                   '<div class="col-xs-4 col-md-4"><input type="radio"  value="0" checked name="IsH5" /> 是</div>',
                   '<div class="col-xs-4 col-md-4"><input type="radio"  value="1" name="IsH5" /> 否</div>',
               '</div>',
                ' <div class="row">',

                '<button class="btn btn-primary" type="button" data-id="0" onclick="$.MGJ.AuthList_V.ValidatorModuleSave(this)" style="float:right;margin-right:80px;">保存</button>',
                //'<button class="btn btn-primary" type="button" onclick="$.MGJ.AuthList_V.AddRow()" style="float:right;margin-right:80px;">添加</button>',
                 '<button class="btn btn-primary" type="button" data-id="0" onclick="$.MGJ.AuthList_V.Ajax_AuthModuleDelete(this)" style="float:right;margin-right:80px;">删除</button>',
            '</div>',


            '</div>',
        '</div>',
    '</div>',

    '</form>'

        ].join("");


        $("#ListWrap").append(html);

    

        eval(
            ["var uploader" + pickerNub + " = WebUploader.create({",
                // swf文件路径
                //swf: BASE_URL + '/js/Uploader.swf',
                // 文件接收服务端。
                //server: 'DBH/UploadImgPath' + "?path=" + path + "&fname=ImageUrl1",

                "server: '/Upload/Upload/',",
                // 选择文件的按钮。可选。 内部根据当前运行是创建，可能是input元素，也可能是flash.
                "pick: {",
                    "id: '#picker' + pickerNub,",
                    "multiple: false",
                "},",
                "accept: {",
                    "title: 'Images',",
                    "extensions: 'gif,jpg,jpeg,bmp,png',",
                    "mimeTypes: 'image/jpg,image/jpeg,image/png'",
                "},",
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                "resize: false",
            "});",
            "LoadItem(eval('uploader'+pickerNub), '#thelist' + pickerNub, '#picker' + pickerNub);"].join("")
        )
    }

    });
})(jQuery);



function LoadItem(item, con, selector) {


    item.on('fileQueued', function (file) {
        item.upload();
    });

    item.on('uploadProgress', function (file, percentage) {

    });

    item.on('uploadSuccess', function (file, r) {
        var result = r._raw;
        var imgurl = result.split("。")[1]; //上传图片的路径
        $(con).children('input[type="hidden"]').val(imgurl);


        var $li = $(
                        '<div  id="' + file.id + '" class="img-thumbnail">' +
                        '<img alt="null" style="width:200px;height:200px;border-radius:5px"/>' +
//                        '<p class="info">' + file.name + '</p>' +
                        '</div>'
                ),
                $img = $li.find('img');


        // $list为容器jQuery实例
        $(con).prepend($li);

        // 创建缩略图
        // 如果为非图片文件，可以不用调用此方法。
        // thumbnailWidth x thumbnailHeight 为 100 x 100
        item.makeThumb(file, function (error, src) {
            if (error) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }
            $img.attr('src', src);
        }, 200, 200);
        $(con + ' > .img-thumbnail').eq(0).mouseenter(function () {
            var url = $(this).find('img').attr('src');
            $(this).attr('name', url).find('img').attr('src', '/Content/webImgs/upLogo/cp_img_sc.png');
        }).mouseleave(function () {
            var url = $(this).attr('name');
            $(this).find('img').attr('src', url);
        }).click(function () {
            $(this).remove();
            $(selector).css('display', 'inline-block');
        });

        $(selector).css('display', 'none');



    });

    item.on('uploadError', function (file) {

    });

    item.on('uploadComplete', function (file) {

    });

}




(function ($) {
    $.fn.extend({
        serializeObject: function () {
            if (this.length > 1) {
                return false;
            }
            var arr = this.serializeArray();
            var obj = new Object;
            $.each(arr, function (k, v) {
                obj[v.name] = v.value;
            });
            return obj;
        }
    });
})(jQuery);



